<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/28
 * Time: 9:59 AM
 */
namespace app\common\helpers;

class Utils
{
    /**
     * 获取客户端IP
     * @return mixed
     */
    public static function getClientIp(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }
    public static function download($url, $path)
    {
        @set_time_limit(0);

        touch($path);

        \Log::info("[File Downloader] Download started, source: $url");
        \Log::info("[File Downloader] ======================================");

        $ctx = stream_context_create([
            "ssl"=>[
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ]);

        if ($fp = fopen($url, "rb", false, $ctx)) {

            if (!$download_fp = fopen($path, "wb", false, $ctx)) {
                return false;
            }

            while (!feof($fp)) {

                if (!file_exists($path)) {
                    // cancel downloading if destination is no longer available
                    fclose($download_fp);

                    return false;
                }

                \Log::info("[Download] 1024 bytes wrote");
                fwrite($download_fp, fread($fp, 1024 * 8 ), 1024 * 8);
            }

            fclose($download_fp);
            fclose($fp);

            \Log::info("[File Downloader] Finished downloading, data stored to: $path");
            \Log::info("[File Downloader] ===========================================");

            return true;
        } else {
            return false;
        }
    }
}